<?php

namespace app\apiadmin\controller\liveManager;

use app\apiadmin\controller\live\Screen;
use app\apiadmin\controller\user\User;
use app\apiadmin\model\behavior\LiveUserMongo;
use app\apiadmin\service\liveManager\LiveManagerService;
use app\apiadmin\service\order\OrderService;
use app\apiadmin\service\statics\LiveRecoderService;
use app\apiadmin\service\statics\LiveUserStaticsService;
use app\apiadmin\service\TCSS\TCSSService;
use app\apiadmin\service\TCSS\TImService;
use app\apiadmin\validate\system\OrderStateValidate;
use app\common\controller\BaseController;
use app\common\service\FrontJwtService;
use app\common\utils\Res;
use think\facade\Db;
use think\facade\Log;

/**
 *  LiveManager 管理直播场次
 *  1 直播列表
 *  2 添加直播
 *  3 修改直播场次
 */
class LiveManager extends BaseController
{

    public function list()
    {
        $param = $this->request->post();
        $result = LiveManagerService::list($param, $this->request->uid);
        return $result;
    }

    /**
     * 添加直播
     *
     * @return \think\response\Json
     */
    public function add()
    {
        $param = $this->request->post();

        $tcss = new TCSSService();
        $imClient = new TImService();

        $task_id = "";
        $groupId = "";

        $record_task_id = "";
        // 检查当前组名是否已经存在
        $seaWhere['del'] = 0;
        $seaWhere['live_group'] = $param['live_group'];
        $exist = LiveManagerService::countWith($seaWhere, 'id');
        if ($exist >= 2) {
            return Res::error("当前组别已经超过两个");
        }
        Db::startTrans();
        try {

            // 处理复播或者复制的任务

            if (isset($param["z_id"])) {
                $zid = $param["z_id"];

                $zinfo = LiveManagerService::get($zid);
                if (!empty($zinfo)) {
                    $zinfo = $zinfo->toArray();
                    // 处理时从直播制数据
                    if ($zinfo["live_type"] == "1") {
                        // 直播转复播 测i是 请属性
                        $param['live_type'] = 0;
                        unset($param["record_task_id"]);
                        unset($param["record_file_id"]);
                        unset($param["record_video_url"]);
                        unset($param["record_status"]);
                    }
                }

                unset($param["service_start_time"]);
                unset($param["service_end_time"]);
                //unset($param["init_people_num"]);

            }

            $stream_app_name = "live";
            $stream_name = md5($param["title"] . date("YmdHis"));

            $course_sale_good_ids = $param["course_sale_id"];
            $live_type = $param["live_type"];

            if ($live_type == "1") {
                // 准备 如果是真的直播任务那么 css_task_id 等于 stream_name
                $param["css_task_id"] = $stream_name;

            } else if ($live_type == "0") {
                // 准备 复播相关的数据
                $info = $tcss->create_live_pull_from_mp4($param["push_file_name"],
                    $stream_name, $param["start_time"], $param["end_time"], $param["title"]);
                $task_id = $info['task_id'];
                $param["css_task_id"] = $task_id;

            }

            $param["stream_app_name"] = $stream_app_name;
            $param["stream_name"] = $stream_name;

            // 这只有 hls的格式 设定直播推理地址
            $param["stream_push_url"] = $tcss->getPushUrl($stream_name, $param["end_time"]);

            $param["stream_play_url"] = json_encode($tcss->getPlayUrl($stream_name, $param["end_time"]));

            // 准备聊天室相关的数据
            $groupId = $imClient->create_live_group("administrator", "AVChatRoom", $param["title"]);
            $param["chatroom_group_id"] = $groupId;

            $init_people_num = $param["init_people_num"];
            unset($param["init_people_num"]);

            //录播任务添加
            if ($live_type == 1 && $param['is_record'] == 1) {
                $res = $tcss->addRecordTask($stream_name, $stream_app_name, $param['start_time'], $param['end_time']);
                if ($res && $res['record_task_id']) {
                    $record_task_id = $res['record_task_id'];
                }
                $param['record_task_id'] = $record_task_id;
            }

            $result = LiveManagerService::add($param);
            if ($result === false) {
                return Res::error("添加失败");
            }

            // redis 设定 处事准备状态
            $liveStatus = new LiveStatus($result);
            $liveStatus->setDefaultStatus(["form" => "add"], $init_people_num);
            $liveStatus->SetLiveIdAndGroupId($result, $groupId);

            //记录开播时间，用于数据大屏展示
            $liveStatus->set_live_starttime($param["start_time"]);
            $liveStatus->set_live_endtime($param["end_time"]);

            // 将id 更新到 redis
            $liveStatus->setGoodIdList($result, $course_sale_good_ids);

            Db::commit();

            return Res::ok("添加成功!");

        } catch (\Exception $e) {

            // 发生异常的时候 删除 TCSS 直播任务和 IM 聊天室 如果是直播拉流任务 则删除直播拉流任务
            // 注意 直播任务 无需删除 任务
            if ($param["live_type"] == "0" && !empty($task_id)) {
                $tcss->delete_pull_stream_task($task_id);
            }

            if (!empty($groupId)) {
                $imClient->delete_live_group($groupId);
            }

            if (!empty($record_task_id)) {
                $tcss->deleteRecordTask($record_task_id);
            }

            Db::rollback();
            // return Res::error("添加失败:" . $e->getMessage());
            throw $e;
        }
    }

    /**
     * 清理关键参数
     *
     * @param array $param
     * @return void
     */
    public function clearField(array &$param)
    {
        unset($param["stream_app_name"]);
        unset($param["stream_name"]);
        unset($param["stream_push_url"]);
        unset($param["css_task_id"]);
        unset($param["stream_play_url"]);
        unset($param["chatroom_group_id"]);
    }

    public function view()
    {
        $id = $this->request->param('id');
        $result = LiveManagerService::get($id);
        return $result;
    }

    public function update()
    {
        $stream_app_name = "live";

        Log::channel("liveInfo")->info("update start:");
        $params = $this->request->post();

        if (!$params["id"]) {
            return Res::error("参数错误");
        }
        if (empty($params["live_group"])) {
            return Res::error("缺少直播分组字段");
        }
        $id = $params['id'];
        unset($params['id']);
        $seaWhere = [
            ['id', 'not in', [$id]],
            ['del', '=', 0],
            ['live_group', '=', $params['live_group']],
        ];

        $seaWhere['live_group'] = $params['live_group'];
        $exist = LiveManagerService::countWith($seaWhere, 'id');
        if ($exist >= 2) {
            return Res::error("当前组别已经超过两个");
        }
        $liveInfo = LiveManagerService::get($id);
        if (empty($liveInfo)) {
            return Res::error("数据不存在");
        }

        if (time() > strtotime($liveInfo["start_time"]) - 600) {
            return Res::error("直播开播前十分钟不能编辑!");
        }

        $liveInfo = $liveInfo->toArray();
        if ($liveInfo["status"] == 1) {
            return Res::error("直播进行中，不能编辑");
        }
        if ($liveInfo["status"] == 2) {
            return Res::error("直播已结束，不能编辑");
        }

        $tcss = new TCSSService();
        $imClient = new TImService();
        Db::startTrans();

        try {

            $init_people_num = $params["init_people_num"];
            unset($params["init_people_num"]);

            // LiveManagerService::del($id);
            if (!empty($liveInfo["css_task_id"])) {
                //$tcss->delete_pull_stream_task($liveInfo["css_task_id"]);
                $tcss->modify_pull_stream_task(
                    $params["css_task_id"],
                    $params["push_file_name"],
                    $params["start_time"],
                    $params["end_time"],
                    $params["title"]
                );
            }
            if (!empty($liveInfo["record_task_id"])) {
                $tcss->deleteRecordTask($liveInfo["record_task_id"]);
                $params['record_task_id'] = '';
                $params['record_file_id'] = '';
                $params['record_video_url'] = '';
                $params['record_status'] = '';
                if ($liveInfo['live_type'] == 1 && $liveInfo['is_record'] == 1) {
                    $res = $tcss->addRecordTask($liveInfo['css_task_id'], $stream_app_name, $liveInfo['start_time'], $liveInfo['end_time']);
                    if (!$res && !$res['record_task_id']) {
                        throw new \Exception("createRecordTask failed");
                    }
                    $params["record_task_id"] = $res['record_task_id'];
                }
            }

            $result = LiveManagerService::update($id, $params);

            $liveStatus = new LiveStatus($result);
            $liveStatus->setDefaultStatus(["form" => "update"], $init_people_num);

            //记录开播时间，用于数据大屏展示
            $liveStatus->set_live_starttime($params["start_time"]);
            $liveStatus->set_live_endtime($params["end_time"]);
            $course_sale_good_ids = $params["course_sale_id"];

            // 将id 更新到 redis
            $liveStatus->setGoodIdList($result, $course_sale_good_ids);

            Db::commit();
            return Res::ok("更新成功");
        } catch (\Throwable $th) {
            Log::channel("liveInfo")->error("update error:" . $th->getMessage());
            Db::rollback();
            throw $th;

            //return Res::error("更新失败:" . $th->getMessage());
        }

    }

    public function del()
    {
        $params = $this->request->post();

        if (!$params["liveId"]) {
            return Res::error("参数错误");
        }

        $id = $params['liveId'];

        // $result = LiveManagerService::del($id);
        $liveInfo = LiveManagerService::get($id);
        if (empty($liveInfo)) {
            return Res::error("数据不存在");
        }
        $liveInfo = $liveInfo->toArray();

        //if ($liveInfo["status"] == 1) {
        //    return Res::error("直播进行中，不能删除");
        //}
        if ($liveInfo["status"] == 2) {
            return Res::error("直播已结束，不能删除");
        }
        //if (time() > strtotime($liveInfo["start_time"]) - 600 && time() < strtotime($liveInfo["start_time"])) {
        //    return Res::error("直播开播前十分钟不能修改!");
        //}

        $tcss = new TCSSService();
        $imClient = new TImService();
        Db::startTrans();

        try {
            LiveManagerService::del($id);
            if (!empty($liveInfo["css_task_id"])) {
                try {
                    $tcss->delete_pull_stream_task($liveInfo["css_task_id"]);
                } catch (\Exception $e) {

                }
            }
            if (!empty($liveInfo["chatroom_group_id"])) {
                //$imClient->delete_live_group($liveInfo["chatroom_group_id"]);
            }
            Db::commit();
            return Res::ok("删除成功");
        } catch (\Throwable $th) {
            Db::rollback();
            throw $th;
            //return Res::error("删除失败");
        }
    }

    public function end()
    {
        $params = $this->request->post();

        if (!$params["liveId"]) {
            return Res::error("参数错误");
        }

        $id = $params['liveId'];

        // $result = LiveManagerService::del($id);
        $liveInfo = LiveManagerService::get($id);
        if (empty($liveInfo)) {
            return Res::error("数据不存在");
        }
        $liveInfo = $liveInfo->toArray();

        if ($liveInfo["status"] == 2) {
            return Res::error("直播已结束，无需关闭");
        }
        if (time() > strtotime($liveInfo["start_time"]) - 600 && time() < strtotime($liveInfo["start_time"])) {
            return Res::error("直播开播前十分钟不能修改!");
        }

        $tcss = new TCSSService();
        $imClient = new TImService();
        Db::startTrans();

        try {

            LiveManagerService::end($id);

            if ($liveInfo["live_type"] == "0") {
                // 关闭 直播任务主动关闭
                $tcss->stop_pull_stream_task($liveInfo["css_task_id"], "pause");
                if (!empty($liveInfo["css_task_id"])) {
                    $tcss->delete_pull_stream_task($liveInfo["css_task_id"]);
                }

            }

            if (!empty($liveInfo["chatroom_group_id"])) {
                // $imClient->delete_live_group($liveInfo["chatroom_group_id"]);
            }
            Db::commit();
            return Res::ok("关闭成功");
        } catch (\Throwable $th) {
            Db::rollback();
            throw $th;
            //return Res::error("关闭失败");
        }
    }

    public function getStatus()
    {
        $id = $this->request->param('liveId');
        if (empty($id)) {
            return Res::error("直播ID不能为空");
        }
        return liveManagerService::getStatus($id);
    }

    // 直播端info接口
    public function liveInfo()
    {
        // 直播端直播信息接口
        $id = $this->request->post('liveId');
        $userId = $this->request->post('userId');
//        $planId = $this->request->post('planId');

        if (empty($id)) {
            return Res::error("直播ID不能为空!");
        }
//        if (empty($planId)) {
        //            return Res::error("邀约ID不能为空!");
        //        }

        $tim = new TImService();
        // 直播信息
        $liveInfo = LiveManagerService::getInfo($id);

        $userinfo = $this->request->frontUerInfo;
        if (empty($userinfo)) {
            if (empty($userId)) {
                return Res::error("用户信息不能为空!");
            }
            $userinfo = DB::table('xh_siyu_user')->where('id=' . $userId)->find();
            $jwtData['front_token'] = FrontJwtService::createToken($userinfo);
            $jwtData['front_token_expireTime'] = 0;
            $jwtData['userinfo'] = $userinfo;
            $liveInfo['token'] = $jwtData;
        }
        if (env('Live.validate_order')) {
            $retUser = OrderService::validate_order($userinfo["id"], $id);
        } else {
            $retUser = ['status' => 0, 'order' => []];
        }
        $liveInfo['valid_order'] = $retUser;
        $d8['remark'] = '看过一场直播以后不让再看这场直播  数据日志***$liveInfo[valid_order]原始=' . json_encode($liveInfo['valid_order']);
        DB::name('siyu_user_remark')->save($d8);

        $yyWhere = [
            'liveId' => $id,
            'user_id' => $userinfo['id'],
        ];
        $yyCount = DB::name('siyu_live_yuyue')->where($yyWhere)->count();
        if ($liveInfo['status'] == 0) {
            //未开播
            if ($yyCount > 0) {
                //已预约
                $liveInfo['yy_status'] = 1;
            } else {
                //未预约
                $liveInfo['yy_status'] = 0;
            }
        }
        $liveInfo['countdown'] = strtotime($liveInfo['start_time']) - time();
        $liveInfo["userInfo"] = [
            "user_id" => User::addPreToAccout($userinfo["id"]),
            "user_name" => $userinfo['nickname'],
            "user_avatar" => $userinfo['wx_avatarurl'],
            "user_sign" => $tim->generateSign(User::addPreToAccout($userinfo["id"])),
        ];

        // 加载 redis中的数据 用户数据
        $liveInfo["offline_user_infos"] = $tim->redis_get_online_user($liveInfo["chatroom_group_id"]);
        $liveInfo["last_msg_list"] = $tim->redis_get_online_msg_all($liveInfo['chatroom_group_id'], 20);
        $liveInfo["total_online_user_num"] = $tim->redis_get_online_user_num($liveInfo['chatroom_group_id']);

        $liveStatus = new LiveStatus($id);

        $vm = $liveStatus->getVMCount($id);
        if ($vm > 0) {
            $liveInfo["total_online_user_num"] += $vm;
        }

        $liveInfo['status_info'] = $liveStatus->getLiveStatus();
        //发起抽奖
        //$liveInfo['ChoujiangStatus'] = $liveStatus->getLiveStatus();

        // 获取实时点赞
        $liveInfo["likely"] = $liveStatus->getLikely($id);

        // 获取商品id 和商品销售
        $liveInfo["good_info"] = $liveStatus->getGoodStatusInfo($id);

        //获取售罄商品列表
        $liveInfo['sell_out_goods_id_list'] = $liveStatus->getSellOutGoodIdList($id);

        //wss
        $liveInfo['wss_host'] = env("WSS.WSS_URL");

        //IM appid
        $liveInfo['im_appid'] = env("Tencent.IMAppId");

        //看过一场直播以后不让再看这场直播功能能 开始  lsh
        $liveInfo['test_data0'] = 'this is a test data0';
        $Where_oli = [
            'del' => 0,
            'id' => $userId,
        ];
        $info_by_userid = DB::name('siyu_user')->where($Where_oli)->find();

        $d1['remark'] = '看过一场直播以后不让再看这场直播  数据日志***$info_by_userid=' . json_encode($info_by_userid);
        DB::name('siyu_user_remark')->save($d1);

        $Where_oli2 = [
            'del' => 0,
            'phone' => $info_by_userid['phone'] ?? '',
        ];
        $info_by_phone = DB::name('siyu_user')->where($Where_oli2)->select();

        $d2['remark'] = '看过一场直播以后不让再看这场直播  数据日志***$info_by_phone=' . json_encode($info_by_phone);
        DB::name('siyu_user_remark')->save($d2);

        $liveUser = new LiveUserStaticsService($id);
        $liveinfo = DB::table('xh_siyu_live_manager')->where('id', $id)->find();
        $flag = false;
        foreach ($info_by_phone as $k => $v) {
            $res = $liveUser->Checkiflook($id, $v['id'], $liveinfo['push_file_name']);
            $d3['remark'] = '本次userid是  ' . $v['id'] . '  看过一场直播以后不让再看这场直播  数据日志***$res=' . json_encode($res);
            DB::name('siyu_user_remark')->save($d3);
            if ($res) {
                $flag = true;
            }
        }
        $d4['remark'] = '看过一场直播以后不让再看这场直播  数据日志***$flag=' . $flag;
        DB::name('siyu_user_remark')->save($d4);

        $d5['remark'] = '看过一场直播以后不让再看这场直播  数据日志***$liveinfo=' . json_encode($liveinfo);
        DB::name('siyu_user_remark')->save($d5);

        $d6['remark'] = '看过一场直播以后不让再看这场直播  数据日志***end_time=' . strtotime($liveinfo['end_time']);
        DB::name('siyu_user_remark')->save($d6);

        $flag1 = false;
        if (time() > strtotime($liveinfo['end_time'])) {
            $flag1 = true;
        }

        if ($flag && $flag1) {
            $liveInfo['live_status_flag'] = 7;
            $liveInfo['valid_order']['status'] = 7;
        } else {
            $liveInfo['live_status_flag'] = 0;
        }

        $d9['remark'] = '看过一场直播以后不让再看这场直播  数据日志***$liveInfo[valid_order]新=' . json_encode($liveInfo['valid_order']);
        DB::name('siyu_user_remark')->save($d9);

        $d7['remark'] = '看过一场直播以后不让再看这场直播  数据日志***最后一行';
        DB::name('siyu_user_remark')->save($d7);

        $liveInfo['test_data'] = 'this is a test data123';

        //看过一场直播以后不让再看这场直播功能能 结束 lsh

        $liveInfo['is_watched_live_content'] = LiveManagerService::isWatchedLiveContent($id, $userId);

        //  $id  $userId
        $IMClient = new TImService();
        if ($liveInfo['is_start_comments'] == 1) {
            $mute = $IMClient->user_mute(env("Live.live_pre") . $userId, $id, 10800, true); // 禁言
            $liveInfo["mute"] = true;
        } else if ($liveInfo['is_start_comments'] == 2) {
            $mute = $IMClient->user_mute(env("Live.live_pre") . $userId, $id, 0, true); // 去掉禁言
            $liveInfo["mute"] = false;
        }

        return Res::ok($liveInfo);
    }

    //
    public function liveInfoLite()
    {
        $id = $this->request->post('liveId');

        if (empty($id)) {
            return Res::error("直播ID不能为空!");
        }

        $tim = new TImService();
        $liveStatus = new LiveStatus(null);

        $liveInfo = [];
        // 直播信息
        $liveInfo_now = LiveManagerService::getInfo($id);

        // 获取助教用户列表
        $userData = DB::name('siyu_sys_member')->where('is_sync_to_im', 1)->select();
        $userList = [];
        foreach ($userData as $item) {
            $userList[] = 'A_' . env("Live.live_pre") . $item['uid'];
        }
        $liveInfo['userList'] = $userList;

        $liveInfo["status"] = $liveInfo_now["status"];
        // 加载 redis中的数据 用户数据
        // $liveInfo["offline_user_infos"] = $tim->redis_get_online_user($liveInfo["chatroom_group_id"]);
        // $liveInfo["last_msg_list"] = $tim->redis_get_online_msg($liveInfo['chatroom_group_id']);
        $liveInfo["total_online_user_num"] = $tim->redis_get_online_user_num($liveInfo_now['chatroom_group_id']);

        //$liveInfo['status_info'] = $liveStatus->getLiveStatus();
        // 获取实时点赞
        $liveInfo["likely"] = $liveStatus->getLikely($id);

        // 获取商品id 和商品销售
        // $liveInfo["good_info"] = $liveStatus->getGoodStatusInfo($id);

        // 在线人数添加初始在线人数
        $liveStatus = new LiveStatus($id);
        $status_info = $liveStatus->getLiveStatus();
        if ($status_info['showOnlineCount'] != 0) {
            $showOnlineCount = json_decode($status_info['showOnlineCount'], true);
            if ($showOnlineCount['num'] > 0) {
                $liveInfo["total_online_user_num"] = $liveInfo["total_online_user_num"] + $showOnlineCount['num'];
            }
        }

        return Res::ok($liveInfo);
    }

    // 中控info接口
    public function liveInfoWithOutUserInfo()
    {
        // 这个接口是场控端用来展示直播参数
        $id = $this->request->post('liveId');

        if (empty($id)) {
            return Res::error("直播ID不能为空");
        }

        $tim = new TImService();
        // 直播信息
        $liveInfo = LiveManagerService::getInfo($id);
        $userInfo = (array) ($this->request->authInfo['data']);

        $uid = $this->request->uid;
        $isImAdmin = $this->request->isImAdmin ?? null;
        $nickname = $userInfo["nick_name"];
        $face = $userInfo["face"];

        $userData = DB::name('siyu_sys_member')->where('is_sync_to_im', 1)->select();
        $userList = [];
        foreach ($userData as $item) {
            $userList[] = 'A_' . env("Live.live_pre") . $item['uid'];
        }
        $liveInfo['userList'] = $userList;

        $liveInfo["userInfo_for_live"] = [
            "member_id" => 'M_' . env("Live.live_pre") . $uid,
            "member_sign" => $tim->generateSign('M_' . env("Live.live_pre") . $uid),
            "control_id" => 'C_' . env("Live.live_pre") . $uid,
            "control_sign" => $tim->generateSign('C_' . env("Live.live_pre") . $uid),
            "admin_id" => 'administrator',
            "admin_sign" => $tim->generateSign('administrator'),
            "user_id" => 'A_' . env("Live.live_pre") . $uid,
            "user_name" => $nickname,
            "user_avatar" => $face,
            "user_sign" => $tim->generateSign('A_' . env("Live.live_pre") . $uid),
            "is_im_admin" => $isImAdmin,
            "front_token" => FrontJwtService::createToken([
                "id" => 'A_' . env("Live.live_pre") . $uid,
                "nickname" => $nickname,
                "wx_avatarurl" => $face,
            ]),
        ];
        $liveInfo["userInfo"] = [
            "user_id" => 'administrator',
            "user_name" => "管理员",
            "user_avatar" => $face,
            "user_sign" => $tim->generateSign('administrator'),
        ];

        // 这里设定中控使用的素具

        // 加载 redis中的数据
        $liveInfo["offline_user_infos"] = $tim->redis_get_online_user($liveInfo["chatroom_group_id"]);
        $liveInfo["last_msg_list"] = $tim->redis_get_online_msg($liveInfo['chatroom_group_id']);
        $liveInfo["last_msg_list_all"] = $tim->redis_get_online_msg_all($liveInfo['chatroom_group_id'], 100);
        $liveInfo["last_illegal_msg_list"] = $tim->redis_get_illegal_msg($liveInfo['chatroom_group_id']);
        $liveInfo["last_silence_msg_list"] = $tim->redis_get_silence_msg($liveInfo['chatroom_group_id']);
        $liveInfo["last_hide_msg_list"] = $tim->redis_get_hide_msg($liveInfo['chatroom_group_id']);
        $liveInfo["total_online_user_num"] = $tim->redis_get_online_user_num($liveInfo['chatroom_group_id']);

        $liveStatus = new LiveStatus($id);
        $liveInfo['guankan_renshu'] = $liveStatus->get_guankan_renshu() ? $liveStatus->get_guankan_renshu() : 0; //累计观看人数

        $liveStatus = new LiveStatus($id);
        $liveInfo['status_info'] = $liveStatus->getLiveStatus();
        // 获取实时点赞
        $liveInfo["likely"] = $liveStatus->getLikely($id);

        // 获取商品id 和商品销售
        $liveInfo["good_info"] = $liveStatus->getGoodStatusInfo($id);

        //获取售罄商品列表
        $liveInfo['sell_out_goods_id_list'] = $liveStatus->getSellOutGoodIdList($id);

        //wss
        $liveInfo['wss_host'] = env("WSS.WSS_URL");

        //IM-Appid
        $liveInfo['im_appid'] = env("Tencent.IMAppId");

        //live_host
        $liveInfo['live_host'] = env("Live.live_host");

        return Res::ok($liveInfo);

    }
    public function liveCallBack()
    {
        //file_put_contents("./LiveCallBack_log.txt", json_encode($this->request->post()) . "\n", FILE_APPEND);
        Log::channel("liveInfo")->info(json_encode($this->request->post()));
        $param = $this->request->post();

        if (!isset($param["event_type"])) {

            return Res::error("参数不正确:event_type");
        }

        $event_type = $param["event_type"];

        if ($event_type === 1 || $event_type === 0) {
            //  这里转到处理 直播的流程
            return $this->LiveCallBackForLive($param);

        }
        if ($event_type === 100 || $event_type === 332) {
            //录播文件事件通知 || 录播状态事件通知
            return $this->LiveRecordCallBack($param);
        }

        if (empty($param["task_id"]) || empty($param["callback_event"]) || empty($param["event_type"])) {
            return Res::error("参数不正确");
        }
        $task_id = $param["task_id"];
        $callback_event = $param["callback_event"];

        $liveManager = new LiveManagerService();

        $ret = false;
        if ($callback_event == "TaskStart") {
            Log::channel("liveInfo")->info("::start TaskStart");
            $ret = $liveManager->updateStatusByTaskId($task_id, 1, time());
        } else if ($callback_event == "TaskExit") {
            Log::channel("liveInfo")->info("::start TaskExit");
            $ret = $liveManager->updateStatusByTaskId($task_id, 2, time());
            // 直播关闭后 清理 redis中的数据
            $Info = $liveManager->getLiveInfoByTaskId($task_id);
            if (!$Info->isEmpty()) {
                //记录数据大屏
                Screen::save_shujukanban($Info->id);

                //打标签去消费
                $ls = new LiveStatus(1);
                $ls->set_dabiaoqian_live($Info->id);

                // $ls = new LiveStatus($Info->id);
                //! todo 这里记得直播完毕后清理 直播数据和状态
                // $ls->cleanStatus();
            }
        }
        if ($ret === true) {
            return Res::jsonResult(["code" => 0]);
        } else {
            return Res::error($ret);
        }

    }

    public function LiveCallBackForLive($param)
    {

        $event_type = $param["event_type"];
        $stream_id = $param["stream_id"];
        $liveManager = new LiveManagerService();

        if ($event_type === 1) {
            Log::channel("liveInfo")->info("::start TaskStart");
            // 直播开始
            $ret = $liveManager->updateStatusByTaskId($stream_id, 1, time());
            if ($ret === true) {
                Log::channel("liveInfo")->info("::start by stream_id: " . $stream_id);
                return Res::jsonResult(["code" => 0]);
            } else {
                Log::channel("liveInfo")->info("::start by stream_id: " . $stream_id . "err");
                Log::channel("liveInfo")->error($ret);
                die("222");
                return Res::error($ret);
            }

        } else {

            $Info = $liveManager->getLiveInfoByTaskId($stream_id);
            if (!$Info->isEmpty()) {
                //记录数据大屏
                Screen::save_shujukanban($Info->id);
            }
        }
        Log::channel("liveInfo")->info("::start other event_type: " . $event_type);
        return Res::jsonResult(["code" => 0]);

    }
    //录播回调
    public function LiveRecordCallBack($param)
    {
        Log::channel("liveInfo")->info("LiveRecordCallBack::param:" . json_encode($param));
        $event_type = $param['event_type'];
        $stream_id = $param["stream_id"];
        $liveManager = new LiveManagerService();
        $info = $liveManager->getLiveInfoByTaskId($stream_id);
        $info = $info->toArray();
        if (!$info) {
            Log::channel("liveInfo")->info("LiveRecordCallBack::live not exists");
            return Res::jsonResult(["code" => 0]);
        }
        switch ($event_type) {
            case '100':
                $record_task_id = $info["record_task_id"];
                $update_data = [
                    'record_file_id' => $param['record_file_id'],
                    'record_video_url' => $param['video_url'],
                    'update_time' => date('Y-m-d H:i:s', time()),
                ];
                break;
            case '332':
                $record_task_id = $info["record_task_id"];
                $update_data = [
                    'record_status' => $param['record_event'],
                    'update_time' => date('Y-m-d H:i:s', time()),
                ];
                break;
            default:
                break;
        }
        if (empty($record_task_id)) {
            Log::channel("liveInfo")->info("LiveRecordCallBack::record_task_id error");
            return Res::jsonResult(["code" => 0]);
        }

        $res = $liveManager->updateRecordByRecordTaskId($record_task_id, $update_data);
        if (!$res) {
            Log::channel("liveInfo")->info("LiveRecordCallBack::update fail record_task_id:{$record_task_id},update_data:" . json_encode($update_data));
        }
        return Res::jsonResult(["code" => 0]);
    }

    public function changeLiveStatus()
    {
        // liveid cmd params
        $param = $this->request->post();
        $uid = $this->request->uid;
        if (empty($param["liveId"]) || empty($param["command"])) {
            return Res::error("参数不正确,请检查参数!!");
        }
        $liveId = $param["liveId"];
        $cmd = $param["command"];
        $params = $param["params"];
        $liveReocde = new LiveRecoderService();

        try {
            $liveStatus = new LiveStatus($liveId, $uid);
            $ret = $liveStatus->ProcessCmd($cmd, $params);

            // 执行完毕如mongodb 执行记录
            $liveReocde->RecodeCommand($liveId, $cmd, $params);

            return Res::ok($ret);
        } catch (\Throwable $th) {
            return Res::error($th->getMessage());
        }
    }

    public function addLikely()
    {
        // liveid cmd params
        $param = $this->request->post();

        if (empty($param["liveId"])) {
            return Res::error("参数不正确,请检查参数!!");
        }
        $liveId = $param["liveId"];
        $num = $param["num"] ?? 0;

        try {
            $liveStatus = new LiveStatus($liveId);
            $ret = $liveStatus->addLikely($liveId, (int) $num);
            return Res::ok($ret);
        } catch (\Throwable $th) {
            return Res::error($th->getMessage());
        }
    }

    public function setImOpenLoginSvc()
    {
        $param = $this->request->post();
        $list = $param["AccountList"];
        $tim = new TImService();
        $addTim = $tim->account_import_many($list);
        return Res::ok($addTim);
    }

    /**
     * 进入直播间 修改订单到课状态
     * @return \think\response\Json
     * @throws \Exception
     * @author cc
     */
    public function setGongyuOrderState()
    {
        $param = $this->request->post();
        file_put_contents("./invitation.txt", "shuashu-signin-setGongyuOrderState:" . json_encode($param) . ' - ' . date('Y-m-d H:i:s'));
        //打日志，做记录
        $m = [];
        $m['liveId'] = $param['live_id'];
        $m['live_user_id'] = $param['union_id']; //用户ID

        $s = db::table('xh_siyu_invitation_user_signin')->where($m)->find();
        if (!$s) {
            $a = [];
            $a['xh_siyu_user.id'] = $m['live_user_id'];
            $a['xh_siyu_invitation_user.liveId'] = $m['liveId'];
            $b = db::table('xh_siyu_invitation_user')
                ->join('xh_siyu_user', 'xh_siyu_invitation_user.wx_unionid = xh_siyu_user.unionid', 'inner')
                ->where($a)->find();

            //到课
            $c = [];
            $c['liveId'] = $param['live_id'];
            $c['live_user_id'] = $param['union_id'];
            $c['signin'] = 0;
            $c['signin_time'] = date('Y-m-d H:i:s');
            if ($b) {
                $c['signin'] = 2;
                $c['signin_time'] = date('Y-m-d H:i:s');
            }

            db::table('xh_siyu_invitation_user_signin')->insertGetId($c);
        }

        $this->validate($param, OrderStateValidate::class);
        $session = Db::table('xh_siyu_live_manager')->where('id', $param['live_id'])->value('venue');
//        $unionId = Db::table('xh_siyu_user')->where('id', $param['union_id'])->value('unionid'); //$param['union_id']   为  xh_siyu_user表的助教ID

        $unionId = Db::table('xh_siyu_user_order_zhujiao_log')->where(['live_id' => $param['live_id'], 'user_id' => $param['union_id']])->field('user_union_id,xh_order_union_id')->find();
        Log::channel("liveInfo")->info("zhujiao_log:" . $param['live_id'] . ' - ' . $param['union_id'] . ' - ' . json_encode($unionId) . ' - ' . date('Y-m-d H:i:s'));

        $unionIds = [];
        if (!empty($unionId)) {
            $unionIds = array_values($unionId);
        }

        $where = [];
        $where[] = ['liveId', '=', $param['live_id']];
        $where[] = ['venue', '=', $session];
        $where[] = ['wx_unionid', 'IN', $unionIds];
        Db::table('xh_siyu_invitation_user')->where($where)->update([
            'signin_status' => 2,
            'signin_time' => date('Y-m-d H:i:s'),
        ]);

        $where = [];
        $where[] = ['wx_union_id', 'IN', $unionIds];
        $where[] = ['pay_state', '=', 1];
        $where[] = ['del', '=', 0];
        $where[] = ['is_association_siyu', '=', 0];
        $where[] = ['pay_time', '<', date('Y-m-d H:i:s')];
        $where[] = ['pingtai', 'IN', [1, 2, 4, 6]];
        $orderArray = Db::table('xh_order_1')->where($where)->column('id,wx_union_id');
        if (!empty($orderArray)) {
            foreach ($orderArray as $value) {
                if (!empty($unionId)) {
                    LiveManagerService::getLiveOrderState($param['live_id'], $session, $value, 2, $value['wx_union_id']);
                }
            }
        }

        $where = [];
        $where[] = ['liveId', '=', $param['live_id']];
        $where[] = ['venue', '=', $session];
        $where[] = ['wx_unionid', 'IN', $unionIds];
        Log::channel("liveInfo")->info("invitation_user:" . json_encode($where) . ' - ' . json_encode($unionIds) . ' - ' . date('Y-m-d H:i:s'));
        $res = Db::table('xh_siyu_invitation_user')->where($where)->update([
            'signin_status' => 2,
            'signin_time' => date('Y-m-d H:i:s'),
        ]);
        Log::channel("liveInfo")->info("invitation_user_signin:" . json_encode($where) . ' - ' . json_encode($res) . ' - ' . date('Y-m-d H:i:s'));

        $where = [];
        $where[] = ['wx_union_id', 'IN', $unionIds];
        $where[] = ['pay_state', '=', 1];
        $where[] = ['del', '=', 0];
        $where[] = ['is_association_siyu', '=', 0];
        $where[] = ['pay_time', '<', date('Y-m-d H:i:s')];
        $where[] = ['pingtai', 'IN', [1, 2, 4, 6]];
        $orderArray = Db::table('xh_order_1')->where($where)->column('id,wx_union_id');

        if (!empty($orderArray)) {
            foreach ($orderArray as $value) {
                if (!empty($unionId)) {
                    LiveManagerService::getLiveOrderState($param['live_id'], $session, $value['id'], 2, $value['wx_union_id']);
                }
            }
        }
        return Res::ok();
    }

    // 直播数据列表
    public function liveStat()
    {
        $param = $this->request->param();

        $id = isset($param['id']) ? $param['id'] : null;
        $live_group = isset($param['live_group']) ? $param['live_group'] : null;
        $limit = isset($param['pageSize']) ? $param['pageSize'] : 10;
        $offset = isset($param['pageNumber']) ? ($param['pageNumber'] - 1) * $limit : 0;
        $liveManagerService = new LiveManagerService();
        $list = $liveManagerService->liveData(compact('limit', 'offset', 'id', 'live_group'));
        return $list;
    }

    // 销售直播数据
    public function liveSellerStat()
    {
        $param = $this->request->param();
        $id = isset($param['id']) ? $param['id'] : null;
        if (empty($param['live_group'])) {
            return Res::error("参数不正确,请检查参数!!");
        }
        $live_group = isset($param['live_group']) ? $param['live_group'] : null;
        $limit = isset($param['pageSize']) ? $param['pageSize'] : 10;
        $offset = isset($param['pageNumber']) ? ($param['pageNumber'] - 1) * $limit : 0;
        $liveManagerService = new LiveManagerService();
        $list = $liveManagerService->liveSellerStat(compact('limit', 'offset', 'id', 'live_group'));
        return $list;
    }

    // 获取公域订单
    public function orderInfo()
    {
        $param = $this->request->param();
        $limit = !isset($param['pageSize']) ? 10 : (int) $param['pageSize'];
        $offset = ($param['pageNumber'] - 1) * $limit;
        $where = [];
        $where[] = ['liveId', '=', $param['liveId']];
        $where[] = ['wx_unionid', '<>', ''];
        $where[] = ['signin_status', '>', 0];
        $unionIds = Db::table('xh_siyu_invitation_user')->where($where)->group('wx_unionid')->column('wx_unionid');
        $orderUnionIdArr = Db::table('xh_siyu_user_order_zhujiao_log')->where('live_id', $param['liveId'])->where('xh_order_union_id', 'in', $unionIds)->group('xh_order_union_id')->column('xh_order_union_id');
        // 获取到课 未在zhujiao_log登录的union_id
        $orderUnionIdArray = array_diff($unionIds, $orderUnionIdArr);
        $userIdArr = Db::table('xh_siyu_user_order_zhujiao_log')->where('live_id', $param['liveId'])->where('user_union_id', 'in', $orderUnionIdArray)->group('user_union_id')->column('user_id');
        $userIdArray = Db::table('xh_siyu_user_order_zhujiao_log')->where('live_id', $param['liveId'])->where('xh_order_union_id', 'in', $unionIds)->group('xh_order_union_id')->column('user_id');
        $userIdArray = array_merge($userIdArray, $userIdArr);
        if (empty($userIdArray)) {
            return Res::ok(['list' => [], 'total' => 0]);
        }
        $liveUserArr = LiveUserMongo::list_array($param['liveId']);
        $liveUserIds = !empty($liveUserArr) ? array_column($liveUserArr, 'live_user_id') : [];
        $unionIdArr = $uidArr = [];
        foreach ($liveUserArr as $value) {
            if (isset($value['wx_unionid']) && !empty($value['wx_unionid']) && in_array($value['live_user_id'], $userIdArray)) {
                switch ($param['type']) {
                    case 'online_15_num1':
                    case 'online_15_num2':
                        if ((isset($value['online_time']) && $value['online_time'] <= (60 * 15)) || !isset($value['online_time']) || empty($value['online_time'])) {
                            if (isset($value['wx_unionid']) && !empty($value['wx_unionid'])) {
                                array_push($unionIdArr, $value['wx_unionid']);
                            }
                            if (isset($value['live_user_id']) && !empty($value['live_user_id'])) {
                                array_push($uidArr, $value['live_user_id']);
                            }
                        }
                        break;
                    case 'online_30_num1':
                    case 'online_30_num2':
                        if (isset($value['online_time']) && $value['online_time'] > (60 * 15) && $value['online_time'] <= (60 * 30)) {
                            if (isset($value['wx_unionid']) && !empty($value['wx_unionid'])) {
                                array_push($unionIdArr, $value['wx_unionid']);
                            }
                            if (isset($value['live_user_id']) && !empty($value['live_user_id'])) {
                                array_push($uidArr, $value['live_user_id']);
                            }
                        }
                        break;
                    case 'online_45_num1':
                    case 'online_45_num2':
                        if (isset($value['online_time']) && $value['online_time'] > (60 * 30) && $value['online_time'] <= (60 * 45)) {
                            if (isset($value['wx_unionid']) && !empty($value['wx_unionid'])) {
                                array_push($unionIdArr, $value['wx_unionid']);
                            }
                            if (isset($value['live_user_id']) && !empty($value['live_user_id'])) {
                                array_push($uidArr, $value['live_user_id']);
                            }
                        }
                        break;
                    case 'online_60_num1':
                    case 'online_60_num2':
                        if (isset($value['online_time']) && $value['online_time'] > (60 * 45) && $value['online_time'] <= (60 * 60)) {
                            if (isset($value['wx_unionid']) && !empty($value['wx_unionid'])) {
                                array_push($unionIdArr, $value['wx_unionid']);
                            }
                            if (isset($value['live_user_id']) && !empty($value['live_user_id'])) {
                                array_push($uidArr, $value['live_user_id']);
                            }
                        }
                        break;
                    case 'online_75_num1':
                    case 'online_75_num2':
                        if (isset($value['online_time']) && $value['online_time'] > (60 * 60) && $value['online_time'] <= (60 * 75)) {
                            if (isset($value['wx_unionid']) && !empty($value['wx_unionid'])) {
                                array_push($unionIdArr, $value['wx_unionid']);
                            }
                            if (isset($value['live_user_id']) && !empty($value['live_user_id'])) {
                                array_push($uidArr, $value['live_user_id']);
                            }
                        }
                        break;
                    case 'online_gt75_num1':
                    case 'online_gt75_num2':
                        if (isset($value['online_time']) && $value['online_time'] > (60 * 75)) {
                            if (isset($value['wx_unionid']) && !empty($value['wx_unionid'])) {
                                array_push($unionIdArr, $value['wx_unionid']);
                            }
                            if (isset($value['live_user_id']) && !empty($value['live_user_id'])) {
                                array_push($uidArr, $value['live_user_id']);
                            }
                        }
                        break;
                }
            }
        }

        $difference = array_diff($userIdArray, $liveUserIds);
        if (!empty($difference) && in_array($param['type'], ['online_15_num1', 'online_15_num2'])) {
            foreach ($difference as $v) {
                $unionId = Db::table('xh_siyu_user')->where('id', $v)->value('unionid');
                array_push($unionIdArr, $unionId);
                array_push($uidArr, $v);
            }
        }

        $orderId = $qwuser = [];
        if (!empty($unionIdArr)) {
            $where = [];
            $where[] = ['live_id', '=', $param['liveId']];
            $where[] = ['user_id', 'in', $uidArr];
            $where[] = ['xh_order_id', '<>', ''];
            $orderId = Db::table('xh_siyu_user_order_zhujiao_log')->where($where)->group('user_id')->column('xh_order_id');
            $qwuser = Db::table('xh_qwuser_1')->where('wx_unionid', 'in', $unionIdArr)->select();
        }
        $teacher = Db::table('xh_qw_sync_user')->where(['qiyeid' => 1, 'status' => 1])->column('userid,name');
        $tearcherDict = [];
        foreach ($teacher as $value) {
            $tearcherDict[$value['userid']] = $value['name'];
        }

        $list = Db::table('xh_order_1')->alias("o")
            ->join('xh_course c', 'o.courseid = c.id', 'left')
            ->join('xh_app_laiyuan l', 'o.laiyuan = l.id', 'left')
            ->join('xh_order_code oc', 'oc.order_id = o.id', 'left')
            ->where('o.id', 'in', $orderId);
        $total = $list->count();
        $list = $list->limit($offset, $limit);
        $orderInfo = $list->field('o.*,c.title as course_title ,c.course_num,l.name as laiyuan_name,oc.teacher_id')->select();

        if ($total == 0) {
            return Res::ok(['list' => [], 'total' => 0]);
        }
        $list = [];
        foreach ($orderInfo as $k => $v) {
            $list[$k]['id'] = $v['id'];
            $list[$k]['short_code'] = $v['short_code'];
            $list[$k]['order_num'] = $v['order_num'];
            $list[$k]['course_title'] = $v['course_title'];
            $list[$k]['course_num'] = $v['course_num'];
            $list[$k]['laiyuan_name'] = $v['laiyuan_name'];
            $list[$k]['teacher_id'] = $v['teacher_id'];
            $list[$k]['pay_time'] = $v['pay_time'];
            $list[$k]['isfinished'] = $v['isfinished'] == 1 ? '已领课' : '未领课';
            $list[$k]['total_fee'] = '¥ ' . $v['total_fee'] / 100;
            $list[$k]['pingtai'] = Db::table('xh_order_pingtai')->where('id', $v['pingtai'])->value('name') ?? '';
            $list[$k]['time'] = $v['time'];
            foreach ($qwuser as $k1 => $v1) {
                if ($v['wx_union_id'] == $v1['wx_unionid'] && $v1['wx_unionid']) {
                    $list[$k]['wx_avatar'] = $v1['wx_avatar'];
                    $list[$k]['wx_name'] = $v1['wx_name'];
                    $list[$k]['wx_userid'] = $v1['wx_userid'];
                }
            }
            if ($v['pay_state'] == 1) {
                $list[$k]['pay_status'] = '已支付';
            } else {
                $list[$k]['pay_status'] = '待支付';
            }
            switch ($v['order_status']) {
                case 1:
                    $list[$k]['order_status_name'] = '正常单';
                    break;
                case 2:
                    $list[$k]['order_status_name'] = '退单中';
                    break;
                case 3:
                    $list[$k]['order_status_name'] = '退单成功';
                    break;
                case 4:
                    $list[$k]['order_status_name'] = '退单失败';
                    break;
                default:
                    $list[$k]['order_status_name'] = '未支付';
                    break;
            }
            $code = Db::table('xh_order_code')->where(['order_id' => $v['id']])->find();
            $list[$k]['open_sms'] = empty($code) ? 0 : $code['open_sms'];
            $list[$k]['open_app'] = empty($code) ? 0 : $code['open_app'];
            $list[$k]['add_code'] = empty($code) ? 0 : $code['add_code'];
            $list[$k]['teacher_id'] = empty($code) ? 0 : $code['teacher_id'];
            $list[$k]['teacher_name'] = empty($code) ? '' : LiveManagerService::getKey($code['teacher_id'], 'userid', 'name', $teacher);

            $tel = $v['tel'];
            if (!empty($tel)) {
                $list[$k]['real_tel'] = '';
                $list[$k]['tel'] = substr_replace($tel, '****', 3, 4);
            } else {
                $list[$k]['real_tel'] = "";
                $list[$k]['tel'] = "";
            }

            $list[$k]['reissue_sms'] = 0;
            $list[$k]['not_send_sms'] = 1;
            $list[$k]['reissue_voice_tel'] = 0;
            $list[$k]['reissue_sms_class'] = '';
            $list[$k]['reissue_sms_disabled'] = '';
            if (!empty($tel) && $v['order_status'] == 1 && $v['isfinished'] != 1 && !empty($v['pay_time'])) {
                $list[$k]['reissue_sms'] = 1;
                if (!empty($v['reissue_sms_time'])) {
                    if ((time() - strtotime($v['reissue_sms_time'])) < 60) {
                        $list[$k]['reissue_sms_class'] = 'layui-btn-disabled';
                        $list[$k]['reissue_sms_disabled'] = 'true';
                    }
                }
                if ($list[$k]['send_sms'] == 1) {
                    $list[$k]['reissue_voice_tel'] = 1;
                }
                $list[$k]['not_send_sms'] = 0;
            }
            if (!empty($v["wx_union_id"])) {
                $zhujiao_list = Db::table('xh_qwuser_1')->field('zhujiao')->where(['wx_unionid' => $v["wx_union_id"], 'delbyuser' => 0, 'delbyzhujiao' => 0])->column('zhujiao');
                $list_zhujiao_old = array_unique($zhujiao_list);
                $old_zhujiao_list = [];
                foreach ($list_zhujiao_old as $k2 => $v2) {
                    if (isset($tearcherDict[$v2]) && !empty($tearcherDict[$v2])) {
                        $old_zhujiao_list[] = $tearcherDict[$v2];
                    }
                }
                $list[$k]["old_zhujiao_list"] = implode('、', $old_zhujiao_list);
            } else {
                $list[$k]["old_zhujiao_list"] = '';

            }
        }
        return Res::ok(['list' => $list, 'total' => $total, 'user_id' => $uidArr, 'user_id_arr' => $userIdArray]);
    }

    // 未参加day2直播名单
    public function day2NotDaoke()
    {
        $param = $this->request->param();
        $limit = !isset($param['pageSize']) ? 10 : (int) $param['pageSize'];
        $offset = ($param['pageNumber'] - 1) * $limit;
        $where = [];
        $where[] = ['wx_unionid', '<>', ''];
        $where[] = ['invitation_status', '>', 0];
        $invitationDay1 = Db::table('xh_siyu_invitation_user')->where($where)->where('liveId', $param['liveDay1'])->group('wx_unionid')->column('wx_unionid');
        $invitationDay2 = Db::table('xh_siyu_invitation_user')->where($where)->where('liveId', $param['liveDay2'])->group('wx_unionid')->column('wx_unionid');
        $invitationArray = array_intersect($invitationDay1, $invitationDay2);
        $where = [];
        $where[] = ['wx_unionid', 'in', $invitationArray];
        $where[] = ['signin_status', '>', 0];
        $signinDay1 = Db::table('xh_siyu_invitation_user')->where($where)->where('liveId', $param['liveDay1'])->group('wx_unionid')->column('wx_unionid');
        $signinDay2 = Db::table('xh_siyu_invitation_user')->where($where)->where('liveId', $param['liveDay2'])->group('wx_unionid')->column('wx_unionid');
        $signinArray = array_diff($signinDay1, $signinDay2);
        if (empty($signinArray)) {
            return Res::ok(['list' => [], 'total' => 0, 'head_data' => []]);
        }
        $log = [];
        $orderUnionIdArr = Db::table('xh_siyu_user_order_zhujiao_log')->where('live_id', $param['liveDay1'])->where('xh_order_union_id', 'in', $signinArray)->group('xh_order_union_id')->column('xh_order_union_id');
        // 获取到课 未在zhujiao_log登录的union_id
        $orderUnionIdArray = array_diff($signinArray, $orderUnionIdArr);
        $log[] = json_encode($orderUnionIdArray);
        $userIdArr = Db::table('xh_siyu_user_order_zhujiao_log')->where('live_id', $param['liveDay1'])->where('user_union_id', 'in', $orderUnionIdArray)->group('user_union_id')->column('user_id');
        $userIdArray = Db::table('xh_siyu_user_order_zhujiao_log')->where('live_id', $param['liveDay1'])->where('xh_order_union_id', 'in', $signinArray)->group('xh_order_union_id')->column('user_id');
        $userIdArray = array_merge($userIdArray, $userIdArr);

        $liveUserArr = LiveUserMongo::list_array((int) $param['liveDay1']);
        $log[] = json_encode($liveUserArr);
        $unionIdArr = [];
        foreach ($liveUserArr as $value) {
            if (isset($value['wx_unionid']) && !empty($value['wx_unionid']) && in_array($value['live_user_id'], $userIdArray)) {
                $unionIdArr[$value['wx_unionid']] = isset($value['online_time']) && $value['online_time'] > 0 ? secondsToHMS($value['online_time']) : '00:00:00';
            }
        }

        $total = count($signinArray);
        $list = [];
        $otherChengjiao = 0;
        foreach ($signinArray as $value) {
            $qwuserInfo = Db::table('xh_qwuser_1')->where('wx_unionid', $value)->find();
            $sender = Db::table('xh_siyu_invitation_user')->where(['liveId' => $param['liveDay1'], 'wx_unionid' => $value])->value('sender');
            $where = [];
            $where[] = ['liveId', 'not in', [$param['liveDay1'], $param['liveDay2']]];
            $where[] = ['wx_unionid', '=', $value];
            $where[] = ['venue', '=', 2];
            $where[] = ['del', '=', 0];
            $invitationArr = Db::table('xh_siyu_invitation_user')->where($where)->select();
            $invitation = $signin = $chengjiao = 0;
            foreach ($invitationArr as $v) {
                if ($v['invitation_status'] > 0) {
                    $invitation++;
                }
                if ($v['signin_status'] > 0) {
                    $signin++;
                }
                if ($v['chengjiao_status'] > 0) {
                    $chengjiao++;
                }
            }
            $list[] = [
                'wx_avatar' => $qwuserInfo ? $qwuserInfo['wx_avatar'] : '',
                'wx_name' => $qwuserInfo ? $qwuserInfo['wx_name'] : '',
                'phone' => $qwuserInfo ? $qwuserInfo['phone'] : '',
                'sender' => Db::table('xh_manager')->where('account', $sender)->value('nick') ?? '',
                'live_online_time' => isset($unionIdArr[$value]) ? $unionIdArr[$value] : '00:00:00',
                'other_invitation' => $invitation,
                'other_signin' => $signin,
                'other_chengjiao' => $chengjiao > 0 ? '是' : '否',
                'union_id' => $value,
            ];
            $otherChengjiao += $chengjiao;
        }
        $where = [];
        $where[] = ['liveId', 'not in', [$param['liveDay1'], $param['liveDay2']]];
        $where[] = ['wx_unionid', 'in', $signinArray];
        $where[] = ['venue', '=', 2];
        $otherYaoyue = Db::table('xh_siyu_invitation_user')->where($where)->group('wx_unionid')->count();
        $headData = [
            'total' => $total,
            'other_yaoyue' => $otherYaoyue,
            'other_chengjiao' => $otherChengjiao,
            'other_chengjiao_lv' => $otherYaoyue > 0 ? number_format($otherChengjiao * 100 / $otherYaoyue, 2) . '%' : '0.00%',
        ];
        return Res::ok(['list' => array_slice($list, $offset, $limit), 'total' => $total, 'headData' => $headData]);
    }
}
